package test.concurrent;

/**
 * 一个死锁的例子（通过同步字符串对象）
 * Created by guoyachao on 2018/6/28.
 */
public class DeadLockSimple extends Thread {

    private String first;

    private String second;

    public DeadLockSimple(String first,String second,String threadName){
        super(threadName);
        this.first = first;
        this.second = second;
    }
    @Override
    public void run() {
        synchronized (first){
            System.out.println(this.getName()+" obtained1:"+first);
            System.out.println(System.identityHashCode(first)); //同一个地址
            try {
                Thread.sleep(1000L);
                synchronized (second){
                    System.out.println(this.getName()+" obtained2:"+second);
                    System.out.println(System.identityHashCode(second));
                }
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }

    public static void main(String[] args) throws InterruptedException {
        String lockA = "lockA";
        String lockB = "lockB";
        System.out.println(System.identityHashCode(lockA));
        System.out.println(System.identityHashCode(lockB));
        DeadLockSimple d1 = new DeadLockSimple(lockA,lockB,"Thread1");
        DeadLockSimple d2 = new DeadLockSimple(lockB,lockA,"Thread2");
        d1.start();
        d2.start();
        d1.join();
        d2.join();
    }
}
